package myjava.algorithm.leetcode;

public class AddBinary {
	
	 public static String addBinary(String a, String b) {
		 
		 String maxString = a.length() > b.length()? a:b;
		 String minString = a.length() > b.length()? b:a;
		 
		 	 
		 StringBuilder sb = new StringBuilder(maxString);
		 StringBuilder sb2 = new StringBuilder(minString);
		 
		 maxString = sb.reverse().toString();
		 minString = sb2.reverse().toString();
		 sb.setLength(0);
		 	 
		 for(int i=0;i<minString.length();i++)
		 {
                     sb.append((char)(maxString.charAt(i) - '0' + minString.charAt(i)));
		 }
		 
		 		 
		 for(int i = minString.length();i < maxString.length();i++)
		 {
                      sb.append(maxString.charAt(i));
		 }
		 
		 		 
		 char[] mainArray = sb.toString().toCharArray();
		 
		 for(int i= 0; i<mainArray.length - 1;i++)
		 {
			 if(mainArray[i] - '0' >= 2)
			 {
				 mainArray[i] = (char)(mainArray[i] - '2' + '0');
				 mainArray[i+1] += 1;
			 }
		 }
		 
		 sb.setLength(0);
		 	 
		 if(mainArray[mainArray.length -1] - '0' >= 2)
		 {
			 mainArray[mainArray.length -1] = (char)(mainArray[mainArray.length -1] - '2' + '0');
			 sb.append(mainArray); 
			 sb.append('1');
		 }
		 else 
		 {
			 sb.append(mainArray); 
		 }
		 
		 return sb.reverse().toString();
		 
	 }
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(addBinary("0","0"));
	}
}
